﻿using System;
using System.Collections;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

//CID 0656 //2010.10.11 //Begin
namespace InfoJetSoft.Service.Worker
{
    //这里假设PGPicker必须使用统一的默认前缀。
    class XSNViewFormatPNGPickerWorker
    {

        public static void formatPNGPicker(View view)
        {
            XmlElement root = view.Doc.DocumentElement;
            //CID 0701 //2010.11.08 //Begin
            string xdServerName = NamespaceUtil.toFullName(view.XdPrefix, "server");
            //CID 0701 //2010.11.08 //End
            string xdBindingName = NamespaceUtil.toFullName(view.XdPrefix, "binding");
            string xdSearchPeopleOnlyName = NamespaceUtil.toFullName(view.XdPrefix, "SearchPeopleOnly");
            string xdAllowMultipleName = NamespaceUtil.toFullName(view.XdPrefix, "AllowMultiple");
            string xdSharePointGroupName = NamespaceUtil.toFullName(view.XdPrefix, "SharePointGroup");

            //CID 0828 //2011.03.10 //Begin
            int index = 0;
            //CID 0828 //2011.03.10 //End

            string objectFilter = "//object[@classid='clsid:61e40d31-993d-4777-8fa0-19ca59b6d0bb']";

            //updated by lishuchao
            //string boxFilter = "table/tr/td/div";
            //string imgFilter = "table/tr/td/button/img";
            string boxFilter = "/SPAN/SPAN/TABLE/TBODY/TR/TD/TABLE/TBODY/TR/TD/DIV";
            //updated by lishuchao

            //CID 0820 //2011.03.30 //Begin
            string attributeFilter = NamespaceUtil.toFullName(view.XslPrefix, "attribute");
            string chooseFilter = NamespaceUtil.toFullName(view.XslPrefix, "choose");
            string whenAttributeFilter = NamespaceUtil.toFullName(view.XslPrefix, "when") + "/" + NamespaceUtil.toFullName(view.XslPrefix, "attribute");
            //CID 0820 //2011.03.30 //End
            XmlNodeList objectElementList = DOMUtil.selectNodes(root, objectFilter, 0, view.NsResolver);
            foreach (XmlElement objectElement in objectElementList)
            {
                //CID 0914 //2011.05.20 //Begin
                string prefix = ParsePrefix(objectElement);
                if (prefix == null)
                {
                    throw new InfoJetException("XSNViewFormatPNGPickerWorker.ParsePrefix.Null");
                }
                //CID 0914 //2011.05.20 //End

                //CID 0701 //2010.11.08 //Begin
                if (view.Manifest.PNGInfoTable == null)
                {
                    view.Manifest.PNGInfoTable = new Hashtable();
                }
                //CID 0733 //2010.12.18 //Begin
                PNGInfo pngInfo = new PNGInfo();
                pngInfo.Server = objectElement.GetAttribute(xdServerName);
                pngInfo.SearchPeopleOnly = objectElement.GetAttribute(xdSearchPeopleOnlyName).ToLower();
                pngInfo.AllowMultiple = objectElement.GetAttribute(xdAllowMultipleName).ToLower();
                //CID 0914 //2011.05.20 //Begin
                if (view.Manifest.SolutionFormatVersion.StartsWith("2.0"))
                {
                    pngInfo.AllowMultiple = "true";
                }
                //CID 0914 //2011.05.20 //End
                pngInfo.SharePointGroup = objectElement.GetAttribute(xdSharePointGroupName);
                //CID 0914 //2011.05.20 //Begin
                pngInfo.Prefix = prefix;
                //CID 0914 //2011.05.20 //End
                string id = view.Manifest.PNGInfoTable.Count.ToString();
                view.Manifest.PNGInfoTable.Add(id, pngInfo);
                //CID 0733 //2010.12.18 //End
                //CID 0701 //2010.11.08 //End

                string binding = objectElement.GetAttribute(xdBindingName);
                if (binding != null && binding.Length > 0)
                {
                    XmlDocument divTempDoc = new XmlDocument();
                    string divXml = templateXml.Replace(":binding:", binding);
                    divXml = divXml.Replace(":delete.gif:", view.Manifest.ImageUri.Delete);
                    //CID 0914 //2011.05.20 //Begin
                    if (pngInfo.Prefix.Length <= 0)
                    {
                        divXml = divXml.Replace(":prefix:", pngInfo.Prefix);
                    }
                    else
                    {
                        divXml = divXml.Replace(":prefix:", pngInfo.Prefix + ":");
                    }
                    //CID 0914 //2011.05.20 //End
                    divTempDoc.LoadXml(divXml);

                    XmlElement divElement = view.Doc.ImportNode(divTempDoc.DocumentElement, true) as XmlElement;

                    //CID 0820 //2011.03.30 //Begin
                    XmlElement chooseElement = DOMUtil.selectANode(objectElement, chooseFilter, view.NsResolver) as XmlElement;
                    if (chooseElement != null)
                    {
                        XmlElement attrElement = DOMUtil.selectOneNode(chooseElement, whenAttributeFilter, view.NsResolver) as XmlElement;
                        if (attrElement.GetAttribute("name").EndsWith("disableEditing"))
                        {
                            attrElement.SetAttribute("name", "disabled");
                        }
                        else
                        {
                            throw new InfoJetException("Unexcepted " + attrElement.GetAttribute("name"), "Picker.disableEditing");
                        }
                        divElement.InsertBefore(chooseElement, divElement.FirstChild);
                    }
                    XmlElement attributeElement = DOMUtil.selectANode(objectElement, attributeFilter, view.NsResolver) as XmlElement;
                    if (attributeElement != null)
                    {
                        divElement.InsertBefore(attributeElement, divElement.FirstChild);
                    }
                    //CID 0820 //2011.03.30 //End

                    XmlElement boxElement = divElement.SelectSingleNode(boxFilter) as XmlElement;
                    boxElement.AppendChild(view.Doc.CreateTextNode(System.Convert.ToChar(0xA0).ToString()));

                    //removed by lishuchao
                    //XmlElement imgElement = divElement.SelectSingleNode(imgFilter) as XmlElement;
                    //imgElement.SetAttribute("src", view.Manifest.ImageUri.AddressBook);

                    //CID 2011.03.10 //Begin
                    //boxElement.SetAttribute(JetConstant.HTML_id, "InfoJet_PNG" + index);
                    //removed by lishuchao

                    index++;
                    //CID 2011.03.10 //End

                    XmlElement trElement = boxElement.ParentNode.ParentNode.ParentNode.ParentNode.ParentNode.ParentNode as XmlElement;
                    //CID 0714 //2010.11.29 //Begin
                    //CID 0858 //2011.03.29 //Begin
                    trElement.SetAttribute(JetConstant.HTML_id, DOMUtil.getControlBindingExpr(view, binding));
                    trElement.SetAttribute("isPicker", "true");
                    //CID 0858 //2011.03.29 //End
                    trElement.SetAttribute("allowMultiple", pngInfo.AllowMultiple);
                    //CID 0714 //2010.11.29 //End
                    //CID 0701 //2010.11.08 //Begin
                    trElement.SetAttribute("pngId", id);
                    //CID 0701 //2010.11.08 //End

                    XmlElement parentElement = objectElement.ParentNode as XmlElement;
                    parentElement.ReplaceChild(divElement, objectElement);
                    string style = objectElement.GetAttribute("style");
                    if (style != null)
                    {
                        divElement.SetAttribute("style", style);
                    }

                }
            }
        }

        //CID 0914 //2011.05.20 //Begin
        private static string ParsePrefix(XmlElement objectElement)
        {
            XmlNodeList paramElementList = objectElement.SelectNodes("param");
            foreach (XmlElement paramElement in paramElementList)
            {
                string name = paramElement.GetAttribute("NAME");
                if (name.Equals("DisplayNameXPath"))
                {
                    string value = paramElement.GetAttribute("VALUE");
                    int index = value.IndexOf(":");
                    if (index > 0)
                    {
                        return value.Substring(0, index);
                    }
                    else
                    {
                        return "";
                    }
                }
            }
            return null;
        }
        //CID 0914 //2011.05.20 //End

        //CID 0828 //2011.03.10 //Begin
        //updated by lishuchao
        //        private static string templateXml = @"
        //<span xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
        //<table style='width:100%'>
        //<tr>
        //<td width='92%'><div class='xdRichTextBox' style='width:100%;height:100%' isItemsContainer='true'>
        //<xsl:for-each select=':binding:/:prefix:Person'>
        //        <xsl:if test='string-length(:prefix:AccountId)'>
        //            <a href='javascript:void(0);' png='true' onclick='return InfoJet_OnPNGItemClick(this);' onkeydown='return InfoJet_OnPNGItemKeyDown(event,this);' onblur='InfoJet_OnPNGItemBlur(this);'>
        //		        <xsl:attribute name='style'>
        //	                display:inline-block;cursor:default;color:#000000;
        //	                <xsl:choose>
        //		                <xsl:when test=':prefix:AccountType = &quot;SharePointGroup&quot;'>FONT-WEIGHT: bold</xsl:when>
        //	                </xsl:choose>
        //                </xsl:attribute>
        //                <xsl:value-of select=':prefix:DisplayName'/>
        //                <img src=':delete.gif:' style='display:none;width:12px;height:12px;border:none;' onclick='InfoJet_OnPNGItemDelete(this);'>
        //                    <xsl:attribute name='acccountId'>
        //                        <xsl:value-of select=':prefix:AccountId'/>
        //                    </xsl:attribute>
        //                </img>
        //	        </a>
        //            <span>; </span>
        //        </xsl:if>
        //</xsl:for-each>
        //</div></td>
        //<td algin='right'><button style='height:20px;width:21px;border:none;background-color:white;' onclick='InfoJet_OnPNGPickerClick(event, this);'><img src=''/></button></td>
        //</tr>
        //</table>
        //</span>";
        //CID 0828 //2011.03.10 //End
        private static string templateXml = @"
<span xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<SPAN>
    <input type='hidden' name='__spPickerHasReturnValue' id='__spPickerHasReturnValue' value='' />
    <input type='hidden' name='__spPickerReturnValueHolder' id='__spPickerReturnValueHolder' value='' />
	<INPUT id='HiddenUserFieldValue' type='hidden' name='HiddenUserFieldValue' value='' />
    <SPAN class='ms-usereditor' id='UserField' EEAfterCallbackClientScript='' ShowEntityDisplayTextInTextBox='0' allowEmpty='1' value='true' RemoveText='Remove' MoreItemsText='More Names...' NoMatchesText='&lt;No Matching Names&gt;' preferContentEditableDiv='true'>
        <TABLE class='ms-usereditor' style='width:288px; BORDER-COLLAPSE: collapse' cellSpacing='0' cellPadding='0' border='0'>
         <TBODY>
          <TR vAlign='bottom'>
           <TD style='WIDTH: 90%' vAlign='top'>
            <TABLE style='TABLE-LAYOUT: fixed; WIDTH: 100%' cellSpacing='0' cellPadding='0' border='0'>
             <TBODY>
              <TR>
               <TD>
                <DIV class='ms-inputuserfield' id='UserField_upLevelDiv' style='border:#dcdcdc 1px solid;OVERFLOW-X: hidden; BACKGROUND-COLOR: window; WORD-WRAP: break-word; HEIGHT: 18px; COLOR: windowtext' onblur='InfoBus_GetUpdatePrincipalsXml(this)' title='People Picker' contentEditable='true' onfocusout='this._fFocus=0;' onfocusin='this._fFocus=1;saveOldEntities(&quot;UserField_upLevelDiv&quot;)' name='upLevelDiv' AutoPostBack='0' onclick='InfoBus_ClickRw(true, true,0,this);' preferContentEditableDiv='true' onfocus='InfoBus_PrincipalChange(this)'>
                    <xsl:for-each select=':binding:/:prefix:Person'>
                        <xsl:if test='string-length(:prefix:AccountId)'>
	                        <SPAN contentEditable='false' style='text-decoration:underline'>
                                <xsl:attribute name='id'>span<xsl:value-of select=':prefix:AccountId'/></xsl:attribute>
                                <xsl:attribute name='class'><xsl:value-of select=':prefix:ResolvedClass'/></xsl:attribute>
                                <DIV id='divEntityData' style='DISPLAY: none'>
                                    <xsl:attribute name='isresolved'><xsl:value-of select=':prefix:IsResolved'/></xsl:attribute>
                                    <xsl:attribute name='description'><xsl:value-of select=':prefix:AccountId'/></xsl:attribute>
                                    <xsl:attribute name='displaytext'><xsl:value-of select=':prefix:DisplayName'/></xsl:attribute>
                                    <xsl:attribute name='key'><xsl:value-of select=':prefix:Key'/></xsl:attribute>
                                    <DIV>
                                    <xsl:attribute name='data'><ArrayOfDictionaryEntry xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><DictionaryEntry><Key xsi:type='xsd:string'>DisplayName</Key><Value xsi:type='xsd:string'><xsl:value-of select=':prefix:DisplayName'/></Value></DictionaryEntry><DictionaryEntry><Key xsi:type='xsd:string'>SPUserID</Key><Value xsi:type='xsd:string'></Value></DictionaryEntry><DictionaryEntry><Key xsi:type='xsd:string'>PrincipalType</Key><Value xsi:type='xsd:string'>User</Value></DictionaryEntry></ArrayOfDictionaryEntry></xsl:attribute>
                                    </DIV>
                                </DIV>
                                <SPAN onmousedown='onMouseDownRw(event);' onclick='' id='content' contentEditable='true'>
                                    <xsl:value-of select=':prefix:DisplayName'/>
                                </SPAN>
                            </SPAN>;
</xsl:if></xsl:for-each></DIV>
                <TEXTAREA onkeydown='return onKeyDownRw(this,&quot;UserField&quot;, 3, true, event);' onkeyup='onKeyUpRw(&quot;UserField&quot;);' title='People Picker' style='border:#ff0000 1px solid; DISPLAY: none; WIDTH: 100%; POSITION: absolute; HEIGHT: 20px' name='$UserField$downlevelTextBox' rows='1' AutoPostBack='0'><xsl:value-of select=':prefix:AccountId'/></TEXTAREA>
               </TD>
              </TR>
             </TBODY>
            </TABLE>
           </TD>
           <TD style='PADDING-LEFT: 5px' vAlign='top'>
            <A title='Check Names' href='javascript:void(0)'><IMG title='Check Names' style='BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px' alt='Check Names' src='/_layouts/images/checknames.gif' ></IMG></A><img src='/_layouts/images/blank.gif' width='8px'/>
            <A title='Browse' id='UserField_Browse' accessKey='B' onclick='__Dialog__InfoBusUserField(event,this,&quot;&quot;); return false;' href='javascript:'><IMG title='Browse' style='BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px' alt='Browse' src='/_layouts/images/addressbook.gif' ></IMG></A>
           </TD>
          </TR>
          <TR>
           <TD colSpan='3'>
            <SPAN class='ms-error'></SPAN>
           </TD>
          </TR>
         </TBODY>
        </TABLE>
    </SPAN></SPAN>
</span>";
    }
}
//CID 0656 //2010.10.11 //End